// pod 'SQLite.swift','~> 0.11.4' 

import SQLite

// 获取doc路径
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
// 创建一个名为db.sqlite3的数据库，并且连接数据库
let db = try Connection("\(path)/db.sqlite3")


// 创建表
let users = Table("users")

let id = Expression<Int64>("id")
let email = Expression<String>("email")
let balance = Expression<Double>("balance")
let verified = Expression<Bool>("verified") 

try db.run(users.create(ifNotExists:true){
     t in 
        t.column(id,primaryKey:true)
        t.column(email,unique:true)
        t.column(name)
})

// insert

// INSERT INTO "users" ("email", "name") VALUES ('alice@mac.com', 'Alice')
try db.run(users.insert(email <- "alice@mac.com", name <- "Alice"))


// update
try db.run(users.update(balance-=10))

let alice = users.filter(id == 1)
try db.run(alice.update(email <- "alice@me.com"))

// query
for user in try db.prepare(users) {
    print("id: \(user[id]), email: \(user[email]), name: \(user[name])")
}

// 异常
do {
    if try db.run(alice.update(email <- "alice@me.com")) > 0 {
        print("updated alice")
    }
} catch {
    print("\(error)")
}